<template>
  <el-form class="main-container-main__form" :model="form" :rules="rules" ref="form" :disabled="loading"
           @submit.native.prevent="doSave({action: 'saveForm', form: 'form'})"
  >
    <el-form-item class="main-container-main__item" prop="mobile" ref="mobile" :error="codeOps.codeError">
      <el-input class="main-container-main__input" v-model="form.mobile" placeholder="请输入手机号" auto-complete="off">
        <template slot="prepend">
          <!--<svg-icon icon-class="login-phone"></svg-icon>-->
          <global-mobile @changeTelArea="changeTelArea"></global-mobile>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item class="main-container-main__item" prop="code" :error="formError" >
      <el-input class="main-container-main__input" v-model="form.code" placeholder="请输入手机验证码" auto-complete="off">
        <template slot="prepend">
          <svg-icon icon-class="login-security"></svg-icon>
        </template>
        <template slot="append">
          <el-button size="medium" @click="sendCode({formItem: 'mobile'})" type="dark" :disabled="sendingCode">
            {{codeBtnText}}
          </el-button>
        </template>
      </el-input>
    </el-form-item>
    <div class="main-container-main__item main-container-main__item--submit">
      <el-button  type="primary" :loading="loading" native-type="submit" block>登录</el-button>
      <Captcha :callback="getResult" :showCaptcha="showCaptcha" :captchaClose="captchaClose"></Captcha>
    </div>
  </el-form>
</template>

<script>

  import {factory, form, getCode} from '@/build';
  import Captcha from '@/components/captcha';

  import {
    getMobileLoginCodeApi as codeApi
  } from "@/services/api/user";

  export default {
    name: "mobile-login",

    mixins: [form, getCode],
    components: {
      Captcha
    },

    data() {
      return {
        codeApi,
        form:{
          mobile: '',
          code: '',
          telArea:"86",
          validate: ''
        },
        rules: {
          mobile: factory.getRule('mobile'),
          code: [
            {required: true,message: '请输入验证码',trigger: 'blur'}
          ]
        },

        formError: '',
      };
    },
    methods:{
      changeTelArea(val){
        this.form.telArea = val;
        this.$refs['form'].validateField('mobile');
      }
    },
    created(){
      this.$store.commit(types.SET_SELECTTELAREA, this.form.telArea);
    },

    mounted() {
      this.bindSave(types.MOBILE_LOGIN, 'saveForm', 'form', {
        beforeSend: (data) => {
          this.formError = '';

          return data;
        },
        callback: ({result, data}) => {
          if (!result) {
            this.formError = data.message;
          } else {

            this.$router.push(this.$route.query.redirect || {
              name: 'home'
            });
          }
        }
      });
    },
    beforeDestroy() {
      this.showCaptcha = false;
    },
  };
</script>
